//
//  JQFXHPlaceholderooTextView.swift
//  RongYiHua
//
//  Created by 卢小艳 on 2025/7/13.
//

import Foundation
import UIKit

class JQFXHPlaceholderooTextView: UITextView {

    var jqfxhPlaceppholder: String? {
        didSet {
            jqfxhPlaceppholderLabel.text = jqfxhPlaceppholder
        }
    }

    var jqfxhPlaceppholderColor: UIColor = .lightGray {
        didSet {
            jqfxhPlaceppholderLabel.textColor = jqfxhPlaceppholderColor
        }
    }

    private lazy var jqfxhPlaceppholderLabel: UILabel = {
        let jqfxhPlaceppholderLabel = UILabel()
        jqfxhPlaceppholderLabel.textColor = jqfxhPlaceppholderColor
        jqfxhPlaceppholderLabel.font = self.font
        jqfxhPlaceppholderLabel.numberOfLines = 0
        jqfxhPlaceppholderLabel.translatesAutoresizingMaskIntoConstraints = false
        return jqfxhPlaceppholderLabel
    }()
    
    

    override var text: String! {
        didSet {
            jqfxhPlaceppholderLabel.isHidden = !text.isEmpty
        }
    }

    override var font: UIFont? {
        didSet {
            jqfxhPlaceppholderLabel.font = font
        }
    }

    override var textContainerInset: UIEdgeInsets {
        didSet {
            updatePlaceholderConstraints()
        }
    }

    override var textContainer: NSTextContainer {
        let container = super.textContainer
        container.lineFragmentPadding = 0 // 关键设置，消除内部左右边距
        return container
    }

    private var jqfxhPlaceppholderConstraints: [NSLayoutConstraint] = []

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        jqfxhSetup()
    }

    

    private func jqfxhSetup() {
        textContainer.lineFragmentPadding = 0 // 关键设置
        addSubview(jqfxhPlaceppholderLabel)
        updatePlaceholderConstraints()
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(textDidChange),
            name: UITextView.textDidChangeNotification,
            object: self
        )
    }
    
    @objc private func textDidChange() {
        jqfxhPlaceppholderLabel.isHidden = !text.isEmpty
    }

    private func updatePlaceholderConstraints() {
        NSLayoutConstraint.deactivate(jqfxhPlaceppholderConstraints)
        jqfxhPlaceppholderConstraints = [
            jqfxhPlaceppholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: textContainerInset.top),
            jqfxhPlaceppholderLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: textContainerInset.left),
            jqfxhPlaceppholderLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -textContainerInset.right)
        ]
        NSLayoutConstraint.activate(jqfxhPlaceppholderConstraints)
    }

    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        jqfxhSetup()
    }
   

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
